<?php

namespace app\api\controller;

use app\admin\model\User;
use app\admin\model\wanlshop\Address;
use app\admin\model\wanlshop\Order;
use app\admin\model\wanlshop\OrderGoods;
use app\admin\model\wanlshop\Pay;
use app\admin\model\wanlshop\Shop;
use App\Api\PrintService;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\Config;
use think\Hook;
use think\Log;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init', 'print'];
    protected $noNeedRight = '*';

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng 经度
     * @param string $lat 纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata' => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata' => $upload,
                'coverdata' => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    public function print($id)
    {
        Log::log("打印：$id");
        $this->model = new \app\admin\model\uniprint\Printer;
        $this->configs = get_addon_config('uniprint');
        $config = new \App\Config\YlyConfig($this->configs['yilianyun']['appid'], $this->configs['yilianyun']['appsecret']);
        Log::log("打印：get_config");

        // 获取token token永不过期
        $uniprint = get_addon_config('uniprint');
        if (empty($uniprint['yilianyun']['access_token'])) {
            $client = new \App\Oauth\YlyOauthClient($config);
            $token = $client->getToken();   //若是开放型应用请传授权码code
            $uniprint['yilianyun']['access_token'] = $token->access_token;
            set_addon_config('uniprint', $uniprint);
        }
        Log::log("打印：get_token");

        $order = Order::where('id', $id)->find();
        $shop = Shop::where('id', $order->shop_id)->value('shopname');
        $goods = OrderGoods::where('order_id', $order->id)->select();
        $pay = Pay::where('order_id', $order->id)->find();
        $user = User::where('id', $order->user_id)->find();
        $address = Address::where('id', $order->address_id)->find();
        Log::log("打印：get_models");
        //调取文本打印
        $content = "<FS2><center>**东火木**</center></FS2>";
        $content .= str_repeat('.', 32);
        $content .= "<FS2><center>--在线支付--</center></FS2>";
        $content .= "<FS><center>$shop</center></FS>";
        $content .= "订单时间:" . date("Y-m-d H:i", $order->createtime) . "\n";
        $content .= "订单编号:$order->order_no \n";
        $content .= str_repeat('*', 14) . "商品" . str_repeat("*", 14);
        $content .= "<table>";
        foreach ($goods as $item) {
            $content .= "<tr><td>{$item['title']}</td><td>{$item['difference']}</td><td>{$item['price']}</td><td>{$item['number']}</td><td>{$item['actual_payment']}</td></tr>";
        }
        $content .= "</table>";
        $content .= str_repeat('.', 32);
        $content .= "应支付金额:￥ {$pay->price} \n";
        $content .= "订单金额:￥ {$pay->order_price} \n";
        if ($pay->freight_price > 0) $content .= "快递金额:￥ {$pay->freight_price} \n";
        if ($pay->coupon_price > 0) $content .= "优惠券金额:￥ {$pay->coupon_price} \n";
        if ($pay->score_price > 0) $content .= "积分抵扣价格:￥ {$pay->score_price} \n";
        if ($pay->oldstaff_price > 0) $content .= "旧物抵扣金额:￥ {$pay->oldstaff_price} \n";
        if ($pay->system_price > 0) $content .= "系统优惠金额:￥ {$pay->system_price} \n";
        if ($pay->invoice_price > 0) $content .= "发票抵扣金额:￥ {$pay->invoice_price} \n";

        $content .= str_repeat('*', 32);
        $content .= "订单总价:￥ {$pay->actual_payment} \n";
        $content .= str_repeat('.', 32);
        $content .= "用户昵称:$user->nickname \n";
        $content .= "手机号:$user->mobile \n";
        $content .= "地址:{$address->formatted_address}{$address->address}{$address->address_name} \n";
        $content .= "<FS2><center>** 完**</center></FS2>";
        Log::log("打印：new PrintService");
        $print = new PrintService($uniprint['yilianyun']['access_token'], $config);
        $data = $print->index('4004769293', $content, '55044541');
        Log::log("打印：content:" . $content . ",res:" . json_encode($data));
    }
}
